const mdutil = require('utils');

function JDSDK(options) {
  if (!(this instanceof JDSDK)) {
    return new JDSDK(options);
  }

  options = options || {};

  if (!options.appKey || !options.secretKey) {
    throw new Error('appKey and secretKey are necessary!');
  }

  this.appKey = options.appKey;
  this.secretKey = options.secretKey;
  this.endpoint = options.endpoint || 'https://router.jd.com/api';
  this.api = {
    queryOrder: 'jd.union.open.order.query',
    queryGoodsPromotionInfo: 'jd.union.open.goods.promotiongoodsinfo.query',
    "getCommonPromotion": "jd.union.open.promotion.common.get",
    "getGoodsCategory": "jd.union.open.category.goods.get",
    "queryGoods": "jd.union.open.goods.query",
    "querySeckillGoods": "jd.union.open.goods.seckill.query",
    "getByUnionidPromotion": "jd.union.open.promotion.byunionid.get",
    "createPosition": "jd.union.open.position.create",
    "queryPosition": "jd.union.open.position.query",
    'queryJingfen': 'jd.union.open.goods.jingfen.query',
    'quan': 'jingdong.union.search.queryCouponGoods',
    "queryCoupon": "jd.union.open.coupon.query"
  };
}

JDSDK.prototype.request = function (params) {
  const {
    method,
    ...rest
  } = params;
  const args = {
    app_key: this.appKey,
    param_json: JSON.stringify(rest),
    access_token: 'e4209eac5db9f8e26a1b2f907fe971a2e51134f051953e27b4bd40ceb48f8adc44148c5089597b5f',
    sign_method: 'md5',
    format: 'json',
    timestamp: this.timestamp(),
    v: "1.0",
    method: method
  };
  args.sign = this.sign(args);
  return new Promise((resolve, reject) => {
    const err = mdutil.checkRequired(params, 'method');

    if (err) {
      reject(err);
    }

    tt.request({
      url: this.endpoint,
      method: 'GET',
      data: args,
      // header:a,
      success: res => {
        if (res.statusCode == 200) {
          resolve(res.data);
        } else {
          reject(res);
        }
      },
      fail: e => {
        reject(e);
      }
    });
  });
};

JDSDK.prototype.execute = function (apiname, params) {
  params.method = apiname;
  return this.request(params).then(res => {
    const field = `${apiname.replace(/\./g, '_')}_response`;
    const resp = res[field];
    resp.result = JSON.parse(resp.result);

    if (resp.result && resp.result.code == 200) {
      return resp.result.data;
    } else {
      console.log('没有数据');
    }
  });
};

JDSDK.prototype.sign = function (params) {
  var sorted = Object.keys(params).sort();
  var basestring = this.secretKey;

  for (var i = 0, l = sorted.length; i < l; i++) {
    var k = sorted[i];
    basestring += k + params[k];
  } // console.log(params)


  basestring += this.secretKey;
  return mdutil.md5(basestring).toUpperCase();
};

JDSDK.prototype.notEmpty = function (obj) {
  // 检验 undefined 和 null 参数检测
  if (!obj || obj == '' || obj == undefined) {
    return false;
  }

  if (Array.prototype.isPrototypeOf(obj) && obj.length === 0) {
    return false;
  }

  if (Object.prototype.isPrototypeOf(obj) && Object.keys(obj).length === 0) {
    return false;
  }

  return true;
};

JDSDK.prototype.funcWhere = function () {
  var errs = new Error().stack;
  console.log(errs);
  var names = new Error().stack.match(/at (.*?) /g);
  var name = names[1].replace('at Object.', '').trim();
  return name;
};

var D = ['queryOrder', 'queryGoodsPromotionInfo', 'getCommonPromotion', 'getGoodsCategory', 'queryGoods', 'querySeckillGoods', 'getByUnionidPromotion', 'createPosition', 'queryPosition', 'queryJingfen', 'quan', 'queryCoupon'];

for (var i = 0; i < D.length; i++) {
  !function (e) {
    JDSDK.prototype[e] = function (data = '') {
      var method = this.api[e];

      if (data && this.notEmpty(data)) {
        return this.execute(method, data);
      }
    };
  }(D[i]);
}

JDSDK.prototype.timestamp = function (d, options) {
  d = d || new Date();

  if (!(d instanceof Date)) {
    d = new Date(d);
  }

  var dateSep = '-';
  var timeSep = ':';

  if (options) {
    if (options.dateSep) {
      dateSep = options.dateSep;
    }

    if (options.timeSep) {
      timeSep = options.timeSep;
    }
  }

  var date = d.getDate();

  if (date < 10) {
    date = '0' + date;
  }

  var month = d.getMonth() + 1;

  if (month < 10) {
    month = '0' + month;
  }

  var hours = d.getHours();

  if (hours < 10) {
    hours = '0' + hours;
  }

  var mintues = d.getMinutes();

  if (mintues < 10) {
    mintues = '0' + mintues;
  }

  var seconds = d.getSeconds();

  if (seconds < 10) {
    seconds = '0' + seconds;
  }

  return d.getFullYear() + dateSep + month + dateSep + date + ' ' + hours + timeSep + mintues + timeSep + seconds;
};

module.exports = JDSDK;